package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 杨林
 * @create 2022-11-03 15:51 星期四
 * description:
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper,Dict> implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Cacheable(value = "dict", key = "'cache_'+#id")  //若缓存中有数据 方法体就不执行
    public List<Dict> findChildData(Long id) {

        //从redis中查询是否存在该部分数据  key==id  value==list
        //List<Dict> dictList = (List<Dict>)redisTemplate.boundValueOps("dict_cache_" + id).get();
//        if (dictList != null && dictList.size() != 0){
//            return dictList;
//        }else{
//            QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("parent_id", id);
//            dictList = dictMapper.selectList(queryWrapper);
//
//            //向list集合中的每个dict对象设置hasChildren
//            for (Dict dict : dictList) {
//                Long dictId = dict.getId();
//                boolean isChildren = this.isChildren(dictId);
//                dict.setHasChildren(isChildren);
//            }


            //将dictList存入到redis中
            //redisTemplate.boundValueOps("dict_cache_" + id).set(dictList, 5L, TimeUnit.MINUTES);
            //return dictList;
        //}
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> dictList = dictMapper.selectList(queryWrapper);

        //向list集合中的每个dict对象设置hasChildren
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChildren = this.isChildren(dictId);
            dict.setHasChildren(isChildren);
        }
        return dictList;
    }


    /**
     * 导出数据字典
     */
    @Override
    public void exportData(HttpServletResponse response) {
        try {
            //设置响应头
            response.setContentType("application/vnd.ms-excel"); //指示相应内容的格式
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("数据字典", "UTF-8"); //中文乱码
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");//附件形式下载

            //查询所有数据字典
            List<Dict> dictList = baseMapper.selectList(null);

            //泛型转换
            List<DictEeVo> dictVoList = new ArrayList<>();
            for (Dict dict : dictList) {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(dict, dictEeVo);
                dictVoList.add(dictEeVo);
            }

            //利用Json字符串进行泛型转换
//            String jsonString = JSONObject.toJSONString(dictList);
//            List<DictEeVo> dictVoList2 = JSONObject.parseArray(jsonString, DictEeVo.class);

            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //注入DictListener
    @Autowired
    private DictListener dictListener;

    /**
     * 导入数据字典
     */
    @Override
    //清除所有dict缓存
    @CacheEvict(value = "dict",allEntries = true,beforeInvocation = true) //方法执行前 将缓存中的数据全部清除
    public void importDictData(MultipartFile file) {

        //向mySQL中导入数据 此时需要清空Redis中的缓存
        //Set keys = redisTemplate.keys("dict_cache_*");
        //redisTemplate.delete(keys);

        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByParentDictCodeAndValue(String dictCode, String value) {
        //如果未传入dictCode 则只根据Value查询
        String name = null;
        if (StringUtils.isEmpty(dictCode)){
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("value", value);
            Dict dict = dictMapper.selectOne(wrapper);
            name = dict.getName();
        }else{
            //根据父节点的dictCode获取父节点
            Dict parentDict = this.getDictByDictCode(dictCode);

            //获取父节点的id
            Long parentId = parentDict.getId();

            //根据parent_id和value获取节点名字
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("parent_id", parentId);
            wrapper.eq("value", value);
            Dict dict = dictMapper.selectOne(wrapper);
            name = dict.getName();
        }
        return name;
    }

    //根据DictCode查询Dict的子节点
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict codeDict = this.getDictByDictCode(dictCode);
        List<Dict> list = this.findChildData(codeDict.getId());
        return list;
    }

    //判断节点是否存在子节点
    private boolean isChildren(Long id){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", id);
        Integer count = dictMapper.selectCount(queryWrapper);
        return count > 0;
    }

    //封装根据dictCode获取Dict 的方法
    private Dict getDictByDictCode(String dictCode){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("dict_code", dictCode);
        Dict dict = dictMapper.selectOne(wrapper);
        return dict;
    }

}
